<?php

namespace App\Service\UserCenter\v1_3_4;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Model\CoinLog;
use App\Model\UserCoin;
use App\Model\UserProfilePersonal;
use App\Model\WhiteHost;
use App\Model\Withdraw;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 提现申请
 */
class WithdrawApplyService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $packageWithdrawRmb = $withdrawRmb = $this->request->input('withdraw_rmb', 0);

        //加入同步锁
        if (RedisUtil::concurrentLock($key = "WithdrawApplyService_{$userId}", 4)) {
            log_info(__CLASS__ . "==withdraw_proccessing==Key:{$key}");
            return $this->setError(ErrorCode::OP_TOO_MANY, '操作太频繁，请勿重复提交！');
        }

        //是否实名认证
        $personalInfo = UserProfilePersonal::getProfile($userId);
        if (!UserProfilePersonal::isFaceVerified($personalInfo)) {
            return $this->setError(ErrorCode::NO_FACE_VRFY, '请先完成实名认证～（如在认证审核中，请通过审核后再提现哦！）');
        }

        //未绑定提现账号
        if (!UserProfilePersonal::isBindAccount($personalInfo)) {
            log_user_result($userId, "NO_BIND_ACCOUNT");
            return $this->setError(ErrorCode::NO_BIND_ACCOUNT, '请先绑定您的收款账号！');
        }

        //超过20元的，走银行卡
        // if ($withdrawRmb >= 20 && !WhiteHost::checkWhite($userId) && !$personalInfo['bank_card']) {
        //     log_user_result($userId, "NO_BIND_BANK_ACCOUNT");
        //     return $this->setError(ErrorCode::NO_BIND_ACCOUNT, '由于渠道变动，请重新绑定您的银行卡收款账号~');
        // }

        $userCoin = UserCoin::getUserInfo($userId);
        $incomeCoin = $userCoin['income_coin'] ?? 0;
        //最大可提现
        $withdrawRmbLmt = Withdraw::getMaxRmbLimit($userId, $incomeCoin);
        if ($withdrawRmb > $withdrawRmbLmt) {
            return $this->setError(ErrorCode::WITHDRAW_OVER_LMT, '提现金币超过当前余额，请重新输入～');
        }
        //提现次数限3次
        $withdrawCount = Withdraw::checkTodayCount($userId);
        if ($withdrawCount >= env('WITHDRAW_TIMES_LIMIT', 3)) {
            return $this->setError(ErrorCode::WITHDRAW_ERROR, "今天已经超过提现次数了哦，明天再来吧～");
        }
        //扣除金币
        $withdrawCoin = Withdraw::checkCostCoin($withdrawRmb);
        //没有额定的提现金币额
        if ($withdrawCoin <= 0) {
            log_user_result($userId, "no_rmb=={$withdrawRmb}");
            return $this->setError(ErrorCode::WITHDRAW_ERROR, "无法申请该额度的提现金币～");
        }
        //实际到账金额
        $withdrawRmb = round($withdrawRmb * (1 - ConfigUtil::getWithdrawFeeRate()), 1);

        Db::beginTransaction();
        try {
            //更新账户
            $remainCoin = UserCoin::decIncome($userId, $withdrawCoin);
            //添加流水记录
            CoinLog::addConsume(
                $userId,
                $withdrawCoin,
                CoinLog::FROM_WITHDRAW,
                $remainCoin
            );
            //记录
            Withdraw::addRecord($userId, $withdrawRmb, $withdrawCoin);
            Db::commit();

            // 检查是否执行秒到账
            /*if (Helper::getSexByIdCard($personalInfo['id_card']) == 2) {
                $secondsWithdrawRet = Withdraw::withdrawMain($this->userId, $packageWithdrawRmb);
                if (isset($secondsWithdrawRet['ret']) && $secondsWithdrawRet['ret'] == 0) {
                    return ['result' => 1, 'tip' => $secondsWithdrawRet['msg']];
                }
            }*/
        } catch (\Throwable $exception) {
            log_info(__CLASS__ . '==withdraw==' . $exception->getMessage());
            Db::rollBack();
            return $this->setError(ErrorCode::WITHDRAW_ERROR, "申请提交出现错误，请联系客服处理～");
        }

        return ['result' => 1, 'tip' => '你的提现申请已提交，等待系统审核~'];
    }
}
